//
//  LoginVC.m
//  AlumniBook
//
//  Created by 喂！ on 2018/10/24.
//  Copyright © 2018年 well. All rights reserved.
//

#import "LoginVC.h"

@interface LoginVC ()

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initFrame];
    [self checkRemember];
    self.view.backgroundColor = [UIColor whiteColor];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self checkLogin];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    


}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:true];
}

-(void)initFrame
{
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.text = @"AlumniBook";
    nameLabel.font = [UIFont systemFontOfSize:64 * SCREEN_SCALE];
    nameLabel.textColor = [UIColor colorWithRed:23/255.0f green:111/255.0f blue:185/255.0f alpha:1.0f];
    [self.view addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).offset(300 * SCREEN_SCALE);
    }];


    
    

    UIView *accountView = [[UIView alloc] init];
    accountView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:accountView];
    [accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_bottom).multipliedBy(655/1334.0f);
        make.width.mas_equalTo(self.view).multipliedBy(454/750.0f);
        make.height.mas_equalTo(accountView.mas_width).multipliedBy(67/454.0f);
    }];

    UIImageView *accountIcon = [[UIImageView alloc] init];
    [accountIcon  setContentHuggingPriority:UILayoutPriorityRequired
                                    forAxis:UILayoutConstraintAxisHorizontal];
    accountIcon.image = [UIImage imageNamed:@"Login_Account"];
    [accountView addSubview:accountIcon];
    [accountIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(accountView);
    }];


    self.accountField.font = [UIFont systemFontOfSize:30 * SCREEN_SCALE];
    self.accountField.textColor = [UIColor colorWithRed:58/255.0f green:59/255.0f blue:59/255.0f alpha:1.0f];
    self.accountField.autocorrectionType = UITextAutocorrectionTypeNo;
    self.accountField.returnKeyType = UIReturnKeyDone;
    self.accountField.delegate = self;
    [accountView addSubview:self.accountField];
    [self.accountField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(accountView);
        make.top.bottom.mas_equalTo(accountIcon);
        make.left.mas_equalTo(accountIcon.mas_right).offset(12);
    }];

    UIView *accountLine = [[UIView alloc] init];
    accountLine.backgroundColor = [UIColor colorWithRed:154/255.0f green:154/255.0f blue:154/255.0f alpha:1.0f];
    [accountView addSubview:accountLine];
    [accountLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.accountField);
        make.bottom.mas_equalTo(accountView);
        make.height.mas_equalTo(0.5);
    }];

    UIView *passwordView = [[UIView alloc] init];
    passwordView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:passwordView];
    [passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.mas_equalTo(accountView);
        make.top.mas_equalTo(accountView.mas_bottom).offset(20 * SCREEN_SCALE);
    }];

    UIImageView *passwordIcon = [[UIImageView alloc] init];
    passwordIcon.image = [UIImage imageNamed:@"Login_Password"];
    [passwordIcon  setContentHuggingPriority:UILayoutPriorityRequired
                                     forAxis:UILayoutConstraintAxisHorizontal];
    [passwordView addSubview:passwordIcon];
    [passwordIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(passwordView);
    }];


    self.passwordField.font = [UIFont systemFontOfSize:30 * SCREEN_SCALE];
    self.passwordField.secureTextEntry = true;
    self.passwordField.returnKeyType = UIReturnKeyDone;
    self.passwordField.textColor = [UIColor colorWithRed:58/255.0f green:59/255.0f blue:59/255.0f alpha:1.0f];
    self.passwordField.delegate = self;
    [passwordView addSubview:self.passwordField];
    [self.passwordField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(passwordView);
        make.top.bottom.mas_equalTo(passwordIcon);
        make.left.mas_equalTo(self.accountField);
    }];

    UIView *passwordLine = [[UIView alloc] init];
    passwordLine.backgroundColor = [UIColor colorWithRed:169/255.0f green:169/255.0f blue:169/255.0f alpha:1.0f];
    [passwordView addSubview:passwordLine];
    [passwordLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.passwordField);
        make.bottom.mas_equalTo(passwordView);
        make.height.mas_equalTo(0.5);
    }];


    [self.rememberButton addTarget:self action:@selector(rememberClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.rememberButton setImage:[UIImage imageNamed:@"Login_UnRemember"] forState:UIControlStateNormal];
    [self.rememberButton setImage:[UIImage imageNamed:@"Login_Remember"] forState:UIControlStateSelected];
    [self.rememberButton setTitle:@"记住密码" forState:UIControlStateNormal];
    [self.rememberButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    self.rememberButton.titleLabel.font = [UIFont systemFontOfSize:26 * SCREEN_SCALE];
    [self.rememberButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 7, 0, 0)];
    [self.rememberButton setTitleColor:[UIColor colorWithRed:169/255.0f green:169/255.0f blue:169/255.0f alpha:1.0f] forState:UIControlStateNormal];
    [self.view addSubview:self.rememberButton];
    [self.rememberButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.accountField);
        make.right.mas_equalTo(self.view.mas_centerX);
        make.height.mas_equalTo(33.5);
        make.top.mas_equalTo(passwordView.mas_bottom).offset(4);
    }];

    UIButton *forgetButton = [[UIButton alloc] init];
    [forgetButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    forgetButton.titleLabel.font = [UIFont systemFontOfSize:26 * SCREEN_SCALE];
    [forgetButton setTitleColor:[UIColor colorWithRed:169/255.0f green:169/255.0f blue:169/255.0f alpha:1.0f] forState:UIControlStateNormal];
    [forgetButton addTarget:self action:@selector(forgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:forgetButton];
    [forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(passwordView);
        make.top.bottom.mas_equalTo(self.rememberButton);
    }];

    
    [self.loginButton addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    self.loginButton.backgroundColor = DefalutBlue;
    [self.view addSubview:self.loginButton];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.rememberButton.mas_bottom).offset(48 * SCREEN_SCALE);
        make.width.mas_equalTo(300 * SCREEN_SCALE);
    }];
    
    [self.registerButton addTarget:self action:@selector(registerClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    self.registerButton.backgroundColor = DefalutBlue;
    [self.view addSubview:self.registerButton];
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.loginButton.mas_bottom).offset(48 * SCREEN_SCALE);
        make.width.mas_equalTo(300 * SCREEN_SCALE);
    }];
}

-(void)checkRemember
{
    NSUserDefaults *userDefatluts = [NSUserDefaults standardUserDefaults];
    NSDictionary *remember = [userDefatluts valueForKey:@"Remember"];
    if (remember) {
        self.accountField.text = [remember valueForKey:@"Account"];
        self.passwordField.text = [remember valueForKey:@"Password"];
        self.rememberButton.selected = true;
    }
}

-(void)rememberClick:(UIButton *)button
{
    button.selected = !button.selected;
    
}

- (void)loginClick:(id)sender {

    NSString *accountStr = self.accountField.text;
    NSString *passwordStr = self.passwordField.text;

    //登录前本地判断用户名账号
    if ([accountStr isEqualToString:@""] || [passwordStr isEqualToString:@""]) {
        [self loginFailed:@"用户名或密码不能为空"];
        return;
    }

    loginAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请求中" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:loginAlert animated:false completion:^{
        NSMutableDictionary *loginDic = [[NSMutableDictionary alloc] init];

        [loginDic setValue:accountStr forKey:@"name"];
        [loginDic setValue:passwordStr forKey:@"password"];

        MoLogin *mologin = [[MoLogin alloc] init];
        [mologin requestToService:loginDic];
        mologin.baseHttpServiceBlock = ^(NSMutableDictionary * dic)
        {
            [self loginSuccess:dic];
        };
    }];
}

- (void)registerClick:(id)sender {
    
        RegisterVC *vc = [RegisterVC new];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
}


-(void)loginSuccess:(NSMutableDictionary *)dic
{
    [loginAlert dismissViewControllerAnimated:false completion:^{
        NSInteger status = [[dic valueForKey:@"Result"] integerValue];

        if (status == 0) {
            
            [self loginFailed:@"登录成功"];//登录失败处理
            NSMutableDictionary *Response = [[dic valueForKey:@"Response"] mutableCopy];
            if (self.rememberButton.selected == true) {
                [Response setValue:@(1) forKey:@"isRemember"];
            }
            else
            {
                [Response setValue:@(0) forKey:@"isRemember"];
            }
            
            UserInfoDao *userInfoDao = [UserInfoDao yy_modelWithJSON:Response];
            [userInfoDao saveToDB];
            [userInfoDao updateToDB];
 
            
            [WellConfig sharedInstance].loginDic = [[NSMutableDictionary alloc] initWithDictionary:[dic valueForKey:@"Response"]];

           

            NSUserDefaults *userDefatluts = [NSUserDefaults standardUserDefaults];
            [userDefatluts setValue:[WellConfig sharedInstance].loginDic forKey:@"loginDic"];
            if (self.rememberButton.selected == true) {
                [userDefatluts setObject:@{@"Account":self.accountField.text,@"Password":self.passwordField.text} forKey:@"Remember"];
            }
            else
            {
                [userDefatluts removeObjectForKey:@"Remember"];
                self.accountField.text = @"";
                self.passwordField.text = @"";
            }
            [userDefatluts synchronize];

            [self startPrepare];

//            [[UIApplication sharedApplication] registerForRemoteNotifications];

        }
        else
        {
            [self loginFailed:[dic valueForKey:@"ErrMsg"]];//登录失败处理
        }
    }];
}

-(void)startPrepare
{
    MainVC *vc = [MainVC new];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
   
}


-(void)loginFailed:(NSString *)str
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录失败" message:str preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:false completion:nil];
}

-(void)forgetPassword
{
//    ForgetPasswordViewController *vc = [[ForgetPasswordViewController alloc] init];
//    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//
//    [self presentViewController:vc animated:false completion:nil];
}



#pragma mark - UITextField
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.accountField) {
        [self.accountField resignFirstResponder];
        [self.passwordField becomeFirstResponder];
    }
    else
    {
        [self.passwordField resignFirstResponder];
        [self loginClick:nil];
    }

    return true;
}

#pragma mark    检查是否已经登录
-(void)checkLogin
{
    NSUserDefaults *userDefatluts = [NSUserDefaults standardUserDefaults];
    [WellConfig sharedInstance].loginDic = [NSMutableDictionary dictionaryWithDictionary:[userDefatluts valueForKey:@"loginDic"]];
    NSArray *keyArray = [[WellConfig sharedInstance].loginDic allKeys];
    if (keyArray.count == 0) {
//        topBackImageView.hidden = YES;
        return;
    }

    MainVC *vc = [MainVC new];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
    
}

#pragma mark    懒加载

-(UIButton *)loginButton
{
    if (!_loginButton) {
        _loginButton = [UIButton new];
    }
    return _loginButton;
}

-(UIButton *)registerButton
{
    if (!_registerButton) {
        _registerButton = [UIButton new];
    }
    return _registerButton;
}

-(UITextField *)accountField
{
    if (!_accountField) {
        _accountField = [UITextField new];
    }
    return _accountField;
}

-(UITextField *)passwordField
{
    if (!_passwordField) {
        _passwordField = [UITextField new];
    }
    return _passwordField;
}

-(UIButton *)rememberButton
{
    if (!_rememberButton) {
        _rememberButton = [UIButton new];
    }
    return _rememberButton;
}




@end
